package net.dreamlu.common;

import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.druid.filter.logging.Slf4jLogFilter;
import com.baidu.ueditor.UeditorConfigKit;
import com.baidu.ueditor.manager.QiniuFileManager;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.core.JFinal;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.ModelRecordElResolver;
import com.jfinal.plugin.activerecord.Sqls;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.druid.DruidStatViewHandler;
import com.jfinal.plugin.druid.IDruidStatViewAuth;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.jfinal.render.ViewType;

import net.dreamlu.common.handler.RenderingTimeHandler;
import net.dreamlu.common.handler.SessionIdHandler;
import net.dreamlu.common.handler.URLOptimizeHandler;
import net.dreamlu.common.handler.XmlHandler;
import net.dreamlu.common.handler.XssHandler;
import net.dreamlu.common.interceptors.JsonExceptionInterceptor;
import net.dreamlu.common.plugin.log.Slf4jLogFactory;
import net.dreamlu.controller.AdminRoutes;
import net.dreamlu.controller.ApiRoutes;
import net.dreamlu.controller.WebRoutes;
import net.dreamlu.interceptor.InstallInterceptor;
import net.dreamlu.model.Options;
import net.dreamlu.model._MappingKit;

/**
 * 项目主要配置部分
 * @author L.cm
 * email: 596392912@qq.com
 * site:  http://www.dreamlu.net
 * @date 2013-5-29 下午9:12:23
 */
public class WebConfig extends JFinalConfig {
	private boolean isDev = false;

	/**
	 * 常量配置
	 */
	@Override
	public void configConstant(Constants me) {
		loadPropertyFile("config.txt");
		
		isDev = getPropertyToBoolean("isdev", false);
		// 开发模式
		me.setDevMode(isDev);
		// 设置Slf4日志
		me.setLogFactory(new Slf4jLogFactory());
		// 使用jsp
		me.setViewType(ViewType.JSP);
		me.setBaseViewPath("/WEB-INF/view");
		
		// 401,403,404,500错误代码处理
		me.setError401View("/WEB-INF/view/error/404.jsp");
		me.setError403View("/WEB-INF/view/error/404.jsp");
		me.setError404View("/WEB-INF/view/error/404.jsp");
		me.setError500View("/WEB-INF/view/error/404.jsp");
	}

	/**
	 * 路由配置
	 */
	@Override
	public void configRoute(Routes me) {
		me.add(new WebRoutes());
		me.add(new ApiRoutes());
		me.add(new AdminRoutes());
	}

	/**
	 * 全局拦截器
	 */
	@Override
	public void configInterceptor(Interceptors me) {
		me.addGlobalActionInterceptor(new JsonExceptionInterceptor());
		me.addGlobalActionInterceptor(new InstallInterceptor());
	}

	/**
	 * 配置处理器
	 */
	@Override
	public void configHandler(Handlers me) {
		if (isDev) {
			me.add(new RenderingTimeHandler());
		}
		me.add(new SessionIdHandler());
		me.add(new URLOptimizeHandler());
		me.add(new XmlHandler());
		// Druid监控
		DruidStatViewHandler druidViewHandler = new DruidStatViewHandler(
				"/admin/druid", new IDruidStatViewAuth() {
			public boolean isPermitted(HttpServletRequest request) {
				return true;
			}
		});
		me.add(druidViewHandler);
		me.add(new XssHandler("/admin")); // `/admin*`为排除的目录
	}
	
	/**
	 * 配置插件
	 */
	@Override
	public void configPlugin(Plugins me) {
		// 数据库信息
		String jdbcUrl  = getProperty("db.jdbcUrl");
		String user	 = getProperty("db.user");
		String password = getProperty("db.password");
		
		// 配置Druid数据库连接池插件
		DruidPlugin druidPlugin = new DruidPlugin(jdbcUrl, user, password);
		druidPlugin.setFilters("stat,wall");
		druidPlugin.addFilter(new Slf4jLogFilter());
		me.add(druidPlugin);

		ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin).setShowSql(isDev);
		_MappingKit.mapping(arp);
		me.add(arp);
		// EhCache
		me.add(new EhCachePlugin());
	}

	@Override
	public void afterJFinalStart() {
		// 用户cookie加密的密钥
		WebUtils.setUserSecret(getProperty("secret"));
		ModelRecordElResolver.setResolveBeanAsModel(true);
		// sqls配置文件
		Sqls.load("sqls.txt");

		// 在JFinal启动时，加入启动时间 ${startTime}
		ServletContext servletContext = JFinal.me().getServletContext();
		servletContext.setAttribute("startTime", new Date());

		// 将Options整个加入到servletContext
		Options.dao.initAll();

		// 线上用qiniu云储存
		if (!isDev) {
			String ak = getProperty("qiniu.ak");
			String sk = getProperty("qiniu.sk");
			String bucket = getProperty("qiniu.bucket");
			UeditorConfigKit.setFileManager(new QiniuFileManager(ak, sk, bucket));
		}
	}

}
